//
//  PopoverSelectionViewController.m
//  ICrEAM
//
//  Created by FoREVer_SaD on 16/11/9.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "PopoverSelectionViewController.h"

#define GAP                   ActualWidth(3)
#define CollectionItemWitdh   ActualWidth(60)
#define CollectionItemHeight  ActualWidth(30)

@interface PopoverSelectionViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UIPopoverPresentationControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation PopoverSelectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    if (self.showType == PopoverSelectionViewShowTypeTable) {
        if(self.dataArray.count > 6)
        {
            self.view.bounds = CGRectMake(0, 0, self.displayWidth, self.displayHeight*6);
        }
        else
        {
            self.view.bounds = CGRectMake(0, 0, self.displayWidth, self.displayHeight*self.dataArray.count);
        }
        
        self.preferredContentSize = self.view.size;
        self.popoverPresentationController.delegate = self;
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.backgroundColor = [UIColor clearColor];
        tableView.delegate = self;
        tableView.dataSource = self;
    
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.scrollEnabled = YES;
        tableView.bounces = YES;
        [self.view addSubview:tableView];
        self.tableView = tableView;
        [self.tableView registerClass:[PopoverSelectionTableViewCell class] forCellReuseIdentifier:@"PopoverSelectionTableViewCell"];
    } else if (self.showType == PopoverSelectionViewShowTypeCollection) {
        CGRect frame;
        if (self.dataArray.count > 7) {
            int row = (self.dataArray.count/7.0);
            frame = CGRectMake(0, 0, ActualWidth(20)+self.displayWidth+(self.displayWidth+GAP)*6.0, ActualWidth(20)+self.displayHeight+(self.displayHeight+GAP)*row);
        } else {
            frame = CGRectMake(0, 0, ActualWidth(20)+self.displayWidth+(self.displayWidth+GAP)*(self.dataArray.count-1.0), ActualWidth(20)+self.displayHeight);
        }
        self.view.bounds = frame;
        self.preferredContentSize = self.view.size;
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(self.displayWidth, self.displayHeight);
        layout.minimumLineSpacing = ActualWidth(3);
        layout.minimumInteritemSpacing = ActualWidth(3);
        layout.sectionInset = UIEdgeInsetsMake(ActualWidth(10), ActualWidth(10), ActualWidth(10), ActualWidth(10));
        
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.bounces = NO;
        [self.view addSubview:collectionView];
        self.collectionView = collectionView;
        [collectionView registerClass:[PopoverSelectionCollectionViewCell class] forCellWithReuseIdentifier:@"PopoverSelectionCollectionViewCell"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.displayHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PopoverSelectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PopoverSelectionTableViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[PopoverSelectionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PopoverSelectionTableViewCell"];
    }
    cell.title = self.dataArray[indexPath.row];
    if(self.isMultiSelect)
    {
        if([self.selectedStr containsString:cell.title])
        {
            cell.backgroundColor = BackgroundColor_HeaderBlue;
        }
        else
        {
            cell.backgroundColor = [UIColor whiteColor];
        }
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(self.isMultiSelect)
    {
        if([self.selectedStr containsString:self.dataArray[indexPath.row]])
        {
            //存在就删除
            NSMutableArray *array = [self.selectedStr componentsSeparatedByString:@";"];
            for(NSString *str in array)
            {
                if([str isEqualToString:self.dataArray[indexPath.row]])
                {
                    [array removeObject:str];
                    break;
                }
            }
            self.selectedStr = [array componentsJoinedByString:@";"];
        }
        else
        {
            //不存在就添加
            [self.selectedStr appendString:[NSString stringWithFormat:@"%@;",self.dataArray[indexPath.row]]];
        }
        [self.tableView reloadData];
        if ([self.delegate respondsToSelector:@selector(getSelectedTitle:)]) {
            [self.delegate getSelectedTitle:self.selectedStr];
        }
    }
    else
    {
        if ([self.delegate respondsToSelector:@selector(getSelectedTitle:)]) {
            [self.delegate getSelectedTitle:self.dataArray[indexPath.row]];
        }
        if ([self.delegate respondsToSelector:@selector(didSelectDataAtIndex:)]) {
            [self.delegate didSelectDataAtIndex:indexPath.row];
        }
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PopoverSelectionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PopoverSelectionCollectionViewCell" forIndexPath:indexPath];
    cell.title = self.dataArray[indexPath.row];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(getSelectedTitle:)]) {
        [self.delegate getSelectedTitle:self.dataArray[indexPath.row]];
    }
    [self dismissViewControllerAnimated:NO completion:nil];

}

@end



#pragma TableViewCell

@interface PopoverSelectionTableViewCell()

@property (nonatomic, strong) UILabel *titleLabel;

@end

@implementation PopoverSelectionTableViewCell

- (void)setTitle:(NSString *)title{
    self.titleLabel.text = title;
    _title = title;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //self.backgroundColor = [UIColor clearColor];
        
        UIView *sep = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 1.0)];
        sep.backgroundColor = SepColor_gray;
        [self.contentView addSubview:sep];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = ContentFont;
        titleLabel.tintColor = ContentTextColor_Black;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel = titleLabel;
        [self.contentView addSubview:titleLabel];
        
        __weak typeof(self) weakSelf = self;
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.mas_left);
            make.top.equalTo(weakSelf.mas_top);
            make.right.equalTo(weakSelf.mas_right);
            make.bottom.equalTo(weakSelf.mas_bottom);
        }];
    }
    return self;
}

@end


@interface PopoverSelectionCollectionViewCell ()

@property (nonatomic, strong) UILabel *titleLabel;

@end


@implementation PopoverSelectionCollectionViewCell

- (void)setTitle:(NSString *)title{
    self.titleLabel.text = title;
    _title = title;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        CornerRadius(self, RadiusValue);
        BorderWidth(self, 1.0);
        BorderColor(self, BorderColor_Gray_Hex);
        
        self.backgroundColor = [UIColor clearColor];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = ContentFont;
        titleLabel.tintColor = ContentTextColor_Black;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel = titleLabel;
        [self.contentView addSubview:titleLabel];
        
        __weak typeof(self) weakSelf = self;
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(weakSelf.mas_width);
            make.height.equalTo(@(ActualHeight(15)));
            make.centerX.equalTo(weakSelf.mas_centerX);
            make.centerY.equalTo(weakSelf.mas_centerY);
        }];
    }
    return self;
}

@end
